<script setup lang="ts">
import store from "@/store";
import { ref, computed } from "vue";
import { ModuleType } from "@/type";
import { deepClone } from "@/utils/utils";
import { ElMessage } from "element-plus";
import { CUSTOM_GROUP } from "@/common";

const groupFormRef = ref();
const dialogVisible = ref(false);
const groupModule = ref<ModuleType>({
  id: "",
  name: "",
  value: "",
  type: "",
  icon: "",
  layout: false,
  children: [],
  attribute: []
});
const customGroup = computed(() => {
  return store.getters.customGroup || [];
});

const checkName = (rule: any, value: string, callback: any) => {
  if (value && customGroup.value.some((node: ModuleType) => node.name === value)) {
    callback(rule.message);
  }
  callback();
};

const rules = ref({
  name: [
    { required: true, message: "请输入节点名称", trigger: "blur" },
    { validator: checkName, message: "自定义组合组件名称重复", trigger: "blur" }
  ],
  icon: { required: true, message: "请输入节点图标", trigger: "blur" }
});

/**
 * 打开
 */
const open = (module: ModuleType) => {
  groupModule.value = module;
  dialogVisible.value = true;
};
/**
 * 关闭
 */
const close = () => {
  dialogVisible.value = false;
};
/**
 * 确定
 */
const confirm = () => {
  groupFormRef.value.validate((valid: boolean) => {
    if (valid) {
      const list = customGroup.value;
      list.push(deepClone(groupModule.value));
      store.commit("setCustomGroup", list);
      localStorage.setItem(CUSTOM_GROUP, JSON.stringify(list));
      ElMessage.success("自定义组合成功");
      close();
    }
  });
};

defineExpose({
  open
});
</script>

<template>
  <el-dialog v-model="dialogVisible" title="XML节点组合" width="500px" @close="close">
    <el-form v-if="dialogVisible" ref="groupFormRef" :model="groupModule" :rules="rules" label-width="auto">
      <el-form-item label="节点名称：" prop="name">
        <el-input v-model="groupModule.name" clearable maxlength="10" placeholder="请输入节点名称" />
      </el-form-item>
      <el-form-item label="节点类型：" prop="type">
        <el-input v-model="groupModule.type" disabled placeholder="请输入节点类型" />
      </el-form-item>
      <el-form-item label="节点布局：" prop="layout">
        <el-input model-value="是布局节点" disabled />
      </el-form-item>
      <el-form-item label="节点图标：" prop="icon">
        <el-input v-model="groupModule.icon" clearable maxlength="30" placeholder="请输入节点图标" />
      </el-form-item>
      <el-form-item label="节点内容：" prop="value">
        <el-input v-model="groupModule.value" type="textarea" maxlength="100" placeholder="请输入节内容" />
      </el-form-item>
    </el-form>
    <div class="flex flex-center">
      <el-button @click="close">取消</el-button>
      <el-button type="primary" @click="confirm">确定</el-button>
    </div>
  </el-dialog>
</template>
